package controllers;

import java.io.IOException;
import java.net.URLDecoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import data.NewsData;

import models.NewsModel;

public class ViewServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String name = URLDecoder.decode(path.replaceAll(request.getServletPath() + "/", ""),"UTF-8");
		
		String[] str = name.split("/");
		if (str.length < 1) {
			response.sendRedirect("/");
			return ;
		}
		
		String id = str[0];
		
		NewsData newsData = new NewsData();
		NewsModel news = newsData.getNews(id);
		
		if (news == null) {
			response.sendRedirect("/msg/page-not-found");
			return ;
		}
		
		request.setAttribute("news", news);
		try {
			request.getRequestDispatcher("/pages/view_news.jsp").forward(request, response);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
